package com.nf.xiaomi.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.nf.xiaomi.entity.OrderEntity;
import com.nf.xiaomi.service.OrderDetailService;
import com.nf.xiaomi.service.OrderService;
import com.nf.xiaomi.service.PayService;
import com.nf.xiaomi.util.AlipayUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PayServiceImpl implements PayService {
    OrderService orderService = new OrderServiceImpl();
    OrderDetailService orderDetailService = new OrderDetailServiceImpl();
    @Override
    public String executePayment(HttpServletRequest request, HttpServletResponse response, Long account, Integer orderID, Integer state) throws AlipayApiException, IOException {
        System.out.println("account = " + account);
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayUtils.gatewayUrl, AlipayUtils.app_id,
                AlipayUtils.merchant_private_key, "json", AlipayUtils.charset,
                AlipayUtils.alipay_public_key, AlipayUtils.sign_type);

        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        List<OrderEntity> orderEntityList = orderService.confirmOrder(account, orderID);
        List<OrderEntity> orderDetailEntityList = orderDetailService.confirmOrder(account, orderID);
        String detailNames = getDetailNames(orderDetailEntityList);
        for (OrderEntity orderEntity : orderEntityList) {
            model.setOutTradeNo(String.valueOf(orderID));
            model.setTotalAmount(String.valueOf(orderEntity.getSumPrice()));
            model.setSubject(detailNames);
        }
        List<String> paramsList = new ArrayList<>();
        paramsList.add("account:"+account+"");
        paramsList.add("state:"+state+"");
        String paramsString = String.join(",", paramsList);
        model.setPassbackParams(paramsString);
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        alipayRequest.setNotifyUrl(AlipayUtils.notify_url+"/order/update");
        alipayRequest.setReturnUrl(AlipayUtils.return_url+"?account="+account);
        alipayRequest.setBizModel(model);
        // 请求
        AlipayTradePagePayResponse alresponse = alipayClient.pageExecute(alipayRequest,"get");
        String body = alresponse.getBody();
        System.out.println(body);
        if(alresponse.isSuccess()){
            System.out.println("支付启动");
        }else {
            System.out.println("支付宝启动失败");
        }
        return body;
    }
}